package org.zerofwk.example.datastruct.linklist;

/**
 * 双向链表测试
 */
public class DlinkedListTest {

    public static void main(String[] args) {
        DlinkedList<Person> dlinkedList = new DlinkedList<>();
        Person p1 = new Person(11, "张三1", "zs1@qq.com");
        Person p2 = new Person(12, "张三2", "zs2@qq.com");
        Person p3 = new Person(13, "张三3", "zs3@qq.com");
        Person p4 = new Person(14, "张三4", "zs4@qq.com");
        //添加测试
        System.out.println("\n原始表：");
        dlinkedList.add(p1);
        dlinkedList.add(p2);
        dlinkedList.add(p3);
        dlinkedList.add(p4);
        dlinkedList.list();

        //删除测试
//        System.out.println("\n删除后：");
//        dlinkedList.del(p4);
//        dlinkedList.list();

        //修改测试
        System.out.println("\n修改后：");
        Person p5 = new Person(14, "张三45", "zs45@qq.com");
        dlinkedList.update(p5);
        dlinkedList.list();
    }
}

class DlinkedList<T> {

    private DlinkNode<T> head = new DlinkNode("");

    public void list() {
        if (head.next == null) {
            System.out.println("链表是空的。");
        }
        DlinkNode<T> temp = head.next;
        while (temp != null) {
            T data = temp.data;
            System.out.println("链表的值：" + data.toString());
            temp = temp.next;
        }
    }

    public void add(T data) {
        DlinkNode<T> dlinkNode = new DlinkNode<>(data);
        DlinkNode<T> temp = head;
        while (temp.next != null) {
            temp = temp.next;
        }
        temp.next = dlinkNode;
        dlinkNode.pre = temp;
    }

    public void del(T delData) {
        if (head.next == null) {
            System.out.println("链表为空，不能删除。");
            return;
        }
        DlinkNode<T> temp = head.next;
        while (temp != null) {
            T curData = temp.data;
            if (curData.equals(delData)) {
                temp.pre.next = temp.next;
                if (temp.next != null) {
                    temp.next.pre = temp.pre;
                }
                break;
            }
            temp = temp.next;
        }
    }

    public void update(T data) {
        if (head.next == null) {
            System.out.println("链表是空的。");
            return;
        }
        DlinkNode<T> temp = head.next;
        boolean isFind = false;
        while (temp != null) {
            T curData = temp.data;
            if (curData.equals(data)) {
                temp.data = data;
                isFind = true;
                break;
            }
            temp = temp.next;
        }
        if(!isFind){
            System.out.println("未找到修改的值。");
        }
    }

    /**
     * 双向链表节点
     *
     * @param <T>
     */
    private class DlinkNode<T> {
        private T data;
        private DlinkNode next;
        private DlinkNode pre;

        public DlinkNode(T data) {
            this.data = data;
            next = pre = null;
        }
    }
}